package main

import (
	"context"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"

	"gitee.com/kitfast/resml"
)

type printableWriter struct {
	w io.Writer
}

func (pw *printableWriter) Write(p []byte) (n int, err error) {
	n, err = pw.w.Write(p)
	log.Printf("Pritable Writer: %d %v", n, err)
	return
}

func main() {
	addr := ":8080"
	root := "/tmp/resource-manager-http-server"
	if os.PathSeparator == '\\' {
		root = `D:\tmp\resource-manager-http-server`
	}
	if argl := len(os.Args); argl > 1 {
		addr = os.Args[1]
		if argl > 2 {
			root = os.Args[2]
		}
	}

	// 文件存储
	files, err := resml.NewOsFileRawStorage(filepath.Join(root, "files"), resml.NewSha256HexEtager(), false)
	if err != nil {
		log.Fatalf("NewOsFileObjectStorage: %v", err)
	}
	files.WithMeta(filepath.Join(root, "metas"))
	// 日志存储
	logs, err := resml.NewOsFileRawStorage(filepath.Join(root, "logs"), resml.NewSha256HexEtager(), true)
	if err != nil {
		log.Fatalf("NewOsFileRawStorage: %v", err)
	}

	mux := http.NewServeMux()
	mux.Handle("/logs/", resml.NewHttpResourceServerHandler("/logs/", logs))
	mux.Handle("/files/", resml.NewHttpResourceServerHandler("/files/", files))
	mux.Handle("/files", resml.NewHttpResourceServerHandler("/files", files))
	mux.Handle("/webui/", resml.NewWebUi("/webui/"))
	mux.HandleFunc("/webui", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "/webui/", http.StatusMovedPermanently)
	})

	svr := &http.Server{Addr: addr, Handler: mux}
	go svr.ListenAndServe()
	signals := make(chan os.Signal, 1)
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
	<-signals
	svr.Shutdown(context.Background())
}
